package com.examplemartin.jpademo.controller.supplier;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.bean.Site;
import com.examplemartin.jpademo.pojo.admin.OperatorLogPO;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.po.good.GoodPO;
import com.examplemartin.jpademo.pojo.po.good.GoodUnit;
import com.examplemartin.jpademo.pojo.po.stock.SummGoodPO;
import com.examplemartin.jpademo.pojo.po.supplier.SupplierPO;
import com.examplemartin.jpademo.service.GoodService;
import com.examplemartin.jpademo.service.SupplierService;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.admin.OperatorLogService;
import com.examplemartin.jpademo.service.stock.SummGoodService;
import com.examplemartin.jpademo.util.EntityCheckUtil;
import com.examplemartin.jpademo.util.SessionUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/supplier")
@Slf4j
public class SupplierController {

    @Resource
    private SupplierService supplierService;
    @Resource
    private GoodService goodService;

    @Resource
    private OperatorLogService operatorLogService;

    @Resource
    private UserService userService;
    @Resource
    private Site site;
    @Resource
    private SummGoodService summGoodService;

    /**
     * 供应商列表
     *
     * @param model
     *
     * @return
     */
    @GetMapping("/supplierlist.do")
    public String SupplierListDo(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                                 Model model) {
        model.addAttribute("title", "供应商列表");

        if (ValidateMember.isEmpty(page) || page == 0) {
            page = 1;
        }

        int pagesize = Integer.parseInt(site.getPageSize());
        if (ValidateMember.isEmpty(pagesize)) {
            pagesize = Integer.MAX_VALUE;
        }
        // 定义 pageable
        Pageable pageable = PageRequest
                .of(page - 1, pagesize, Sort.by("createTime").descending().and(Sort.by("id").descending()));
//        List<SupplierPO> all = supplierService.findAll();
//        model.addAttribute("supplierlist",all);
        // 获取分页
        List<SupplierPO> allPage = supplierService.findAllPage(pageable);
        // 计算日志总条数
        Long logSize = supplierService.countAll();

        Long totalPage = logSize / pagesize;
        if (totalPage * pagesize < logSize) {
            totalPage++;
        }
        Integer currentPage = page;
        model.addAttribute("supplierlist", allPage);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);

        // 是否出现 前省略号
        Boolean befor_ellipsis = false;
        if (currentPage >= 4) {
            befor_ellipsis = true;
        }
        model.addAttribute("befor_ellipsis", befor_ellipsis);
        // 是否出现 前省略号
        Boolean after_ellipsis = false;
        if ((totalPage - currentPage) > 3) {
            after_ellipsis = true;
        }
        model.addAttribute("after_ellipsis", after_ellipsis);

        // b1 -- current -- a1
        // 分页b1 是否出现
        Boolean b1 = false;
        if (currentPage <= 2) {
            b1 = true;
        }
        model.addAttribute("b1", b1);
        // 分页a1 是否出现
        Boolean a1 = false;
        if ((totalPage - currentPage) <= 2) {
            a1 = true;
        }
        model.addAttribute("a1", a1);
        // 返回最后3页页码
        model.addAttribute("last00", totalPage - 1);
        model.addAttribute("last01", totalPage - 2);
        model.addAttribute("last02", totalPage - 3);
        // 中间页码
        model.addAttribute("mida", currentPage + 1);
        model.addAttribute("midb", totalPage - 1);

        // 中间分页
        Boolean mid = false;
        if (!b1 && !a1) {
            mid = true;
        }
        model.addAttribute("mid", mid);


        return "supplier/supplierlist";
    }

    /**
     * 跳转到添加供应商 get
     *
     * @param model
     *
     * @return
     */
    @GetMapping("/addsupplier.do")
    public String addSupplierDo(Model model) {
        model.addAttribute("title", "新建供应商");
        return "supplier/addsupplier";
    }

    /**
     * 添加供应商addSupplierAjax Ajax
     *
     * @param supplierPO
     *
     * @return
     */

    @PostMapping("/addsupplier.ajax")
    @ResponseBody
    public AjaxResult addSupplierAjax(@RequestBody SupplierPO supplierPO) {

        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        operatorLogPO.setUser(loninUser);
        operatorLogPO.setCreateTime(new Date());


        // 01 实体检测
        AjaxResult check = EntityCheckUtil.check(supplierPO);
        if (check.getCode() != 200) {
            operatorLogPO.setContent("添加供应商操作--" + check.getMsg());
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, check.getMsg());
        }

        // 02 供应商是否重名
        List<SupplierPO> allByName = supplierService.findAllByName(supplierPO.getName());
        if (allByName != null && allByName.size() > 0) {
            operatorLogPO.setContent("添加供应商操作失败--" + supplierPO.getName() + "--重名");
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, "添加供应商操作失败--" + supplierPO.getName() + "--重名");
        }

        log.info("供应商" + supplierPO);
        supplierPO.setCreateTime(new Date());
        SupplierPO save = supplierService.save(supplierPO);

        if (save == null) {
            operatorLogPO.setContent("添加供应商操作--" + supplierPO.getName() + ": 供应商添加错误,请联系管理员");
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, "添加供应商操作--" + supplierPO.getName() + ": 供应商添加错误,请联系管理员");
        }

        operatorLogPO.setContent("成功添加新供应商--" + supplierPO.getName());
        operatorLogService.saveLog(operatorLogPO);
        return AjaxResult.success(200, "成功添加新供应商", null);
    }

    /**
     * 禁用供应商 forbidden.ajax
     *
     * @param supplierPO
     *
     * @return
     */
    @PostMapping("/forbidden.ajax")
    @ResponseBody
    public AjaxResult forbiddenAjax(@RequestBody SupplierPO supplierPO) {

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());
        operatorLogPO.setUser(loninUser);
        operatorLogPO.setCreateTime(new Date());

        SupplierPO byId = supplierService.findById(supplierPO.getId());
        if (byId == null) {
            operatorLogPO.setContent("修改供应商状态 " + byId.getName() + " 有误");
            operatorLogService.saveLog(operatorLogPO);
            AjaxResult.fail(500, "不能切换状态,传入数据有误");
        }

        byId.setStatus(SupplierPO.SUPPLIER_STATUS_LOCKED);
        operatorLogPO.setContent("禁用供应商" + byId.getName());
        operatorLogService.saveLog(operatorLogPO);

        supplierService.save(byId);


        return AjaxResult.success(200, "已禁用", null);
    }

    /**
     * 跳转到编辑 editsupplier.do
     *
     * @param id
     *
     * @return
     */
    @GetMapping("/editsupplier.do")
    public String editSupplierDo(Long id, Model model) {
        model.addAttribute("title", "编辑供应商信息");
        SupplierPO byId = supplierService.findById(id);
        model.addAttribute("supplier", byId);
        return "supplier/editsupplier";

    }

    /**
     * 编辑修改 editsupplier.ajax
     */
    @PostMapping("/editsupplier.ajax")
    @ResponseBody
    public AjaxResult editSupplierAjax(@RequestBody SupplierPO supplierPO) {

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        UserPO loginUser = SessionUtil.getLoninUser();
        loginUser = userService.findUserById(loginUser.getId());
        operatorLogPO.setUser(loginUser);
        operatorLogPO.setCreateTime(new Date());

        SupplierPO byId = supplierService.findById(supplierPO.getId());

        byId.setName(supplierPO.getName());
        byId.setStatus(supplierPO.getStatus());
        byId.setAddress(supplierPO.getAddress());
        byId.setLinkman(supplierPO.getLinkman());
        byId.setPhone(supplierPO.getPhone());
        byId.setComment(supplierPO.getComment());
        byId.setEmail(supplierPO.getEmail());
        byId.setUpdateTime(new Date());


        AjaxResult check = EntityCheckUtil.check(byId);
        if (check.getCode() != 200) {
            operatorLogPO.setContent("修改供应商: " + supplierPO.getName() + " 失败:" + check.getMsg());
            operatorLogService.saveLog(operatorLogPO);
            return AjaxResult.fail(500, check.getMsg());
        }

        supplierService.save(byId);

        operatorLogPO.setContent("成功修改供应商: " + supplierPO.getName());
        operatorLogService.saveLog(operatorLogPO);

        return AjaxResult.success(200, "成功修改", null);
    }

    /**
     * 跳转到  供应商<->商品列表
     * supplierandgoodlist.do
     */
    @GetMapping("/supplierandgoodlist.do")
    public String SupplierAndGoodListDo(@RequestParam(name = "getid", required = false) String getid, Model model) {

        model.addAttribute("title", "供应商<->商品");
        List<SupplierPO> all = supplierService.findAllByStatus(SupplierPO.SUPPLIER_STATUS_NORMAL);
        model.addAttribute("supplierlist", all);

        List<GoodPO> othergoodlist = new ArrayList<GoodPO>();
        List<GoodPO> owngoodlist = new ArrayList<GoodPO>();
        SupplierPO byId = null;
        if (!ValidateMember.isEmpty(getid)) {
            Long id = Long.parseLong(getid);
            byId = supplierService.findById(id);
            List<GoodPO> good = byId.getGood();
            List<GoodPO> allgood = goodService.findAllByStatus(GoodPO.GOOD_STATUS_NORMAL);


            for (GoodPO item : allgood) {

                for (GoodPO goodPO : good) {
                    if (item.getId() == goodPO.getId()) {
                        owngoodlist.add(item);
                        break;
                    }
                }
            }

            othergoodlist.addAll(allgood);
            for (GoodPO item : owngoodlist) {
                othergoodlist.remove(item);
            }


            model.addAttribute("othergoodlist", othergoodlist);
            model.addAttribute("owngoodlist", owngoodlist);
            model.addAttribute("current_supplier_id", id);

            SupplierPO currentsupplier = supplierService.findById(id);
            model.addAttribute("currentsupplier", currentsupplier);
            model.addAttribute("unitname", GoodUnit.UNIT_NAME);
        }


        return "supplier/supplierandgoodlist";
    }

    /**
     * add_good_to_supplier.ajax
     * 添加 商品到 供应商
     */
    @PostMapping("/add_good_to_supplier.ajax")
    @ResponseBody
    public AjaxResult addGoodToSupplierAjax(@RequestBody SupplierPO supplier) {

        SupplierPO supplierPO = supplierService.findById(supplier.getId());

        OperatorLogPO operatorLogPO = new OperatorLogPO();
        UserPO loninUser = SessionUtil.getLoninUser();
        loninUser = userService.findUserById(loninUser.getId());
        operatorLogPO.setUser(loninUser);
        operatorLogPO.setCreateTime(new Date());


        if (supplierPO.getGood() == null) {
            supplierPO.setGood(new ArrayList<GoodPO>());
        }

        if (supplier.getGood().size() <= 0) {
            return AjaxResult.fail(500, "请选择要添加的商品");
        }

        for (GoodPO goodPO : supplier.getGood()) {
            GoodPO byId = goodService.findById(goodPO.getId());
            supplierPO.getGood().add(byId);
        }

        // 后备 处理 -- 在summ表中如果不存在商品信息, 则添加
        for (GoodPO goodPO : supplier.getGood()) {
            SummGoodPO byGoodPO = summGoodService.findByGoodPO(goodPO);
            if (byGoodPO == null) {
                SummGoodPO summGoodPO = new SummGoodPO();
                summGoodPO.setGoodPO(goodPO);
                summGoodPO.setGoodcount(0);
                summGoodPO.setGoodspare(0);
                summGoodService.save(summGoodPO);
            }
        }

        supplierPO.setCreateTime(supplierPO.getCreateTime());
        supplierPO.setUpdateTime(new Date());
        operatorLogPO.setCreateTime(new Date());
        operatorLogPO.setContent("编辑供应商: " + supplierPO.getName() + " 的商品关联表");
        operatorLogService.saveLog(operatorLogPO);

        supplierService.save(supplierPO);


        return AjaxResult.success(200, "添加成功", null);
    }

    /**
     * 从供应商商品列表移除商品
     * removegood.ajax
     */
    @PostMapping("/removegood.ajax")
    @ResponseBody
    public AjaxResult removeGoodAjax(@RequestBody SupplierPO supplier) {

        List<GoodPO> good = supplier.getGood();
        if (ValidateMember.isEmpty(good) || good.size() <= 0) {
            return AjaxResult.fail(500, "请选择要移除的商品");
        }

        SupplierPO byId = supplierService.findById(supplier.getId());

        for (GoodPO goodPO : good) {
            GoodPO byIdGood = goodService.findById(goodPO.getId());
            byId.getGood().remove(byIdGood);
        }

        supplierService.save(byId);

        return AjaxResult.success(200, "成功移除商品", null);
    }


}
